﻿using MeterReader.WebApi.Models;
using Microsoft.EntityFrameworkCore;

namespace MeterReader.WebApi.Services.Repositories
{
    public class Repository : IRepository
    {
        private readonly MyDbContext _context;
        private readonly int _meterCount;

        public Repository(MyDbContext newDbContext, int meterCount)
        {
            _context = newDbContext;
            _meterCount = meterCount;
            NewTMeterListInit();
        }

        public async Task<List<string>> GetMeterListAsync() => await _context.NewTMeterList.Select(x => x.Name).ToListAsync();

        public async Task SaveDataAsync(IEnumerable<NewTMeter> newTMeters)
        {
            foreach (var newTMeter in newTMeters)
            {
                _context.Add(newTMeter);
            }
            await _context.SaveChangesAsync();
        }

        public async Task<List<PointsInfo>> SearchAsync(string name, DateTime start, DateTime end)
        {
            var meter = await _context.NewTMeterList.Where(p => p.Name == name).Include(p => p.NewTMeters).FirstOrDefaultAsync();
            return meter!
                .NewTMeters.Where(t => t.Timestamp >= start && t.Timestamp <= end)
                .Select(t => new PointsInfo() { Value = t.Value, Time = t.Timestamp })
                .ToList();
        }

        private void NewTMeterListInit()
        {
            if (_meterCount >= 0 && _context != null)
            {
                var meterNames = _context.NewTMeterList.ToList();
                //表中有 N1 个标记为使用的电表
                var useCount = meterNames.Count(m => m.IsDeleted == false);
                //配置和使用电表数相同，直接退出
                if (Equals(useCount, _meterCount))
                    return;
                //表中有 N2 个电表
                var currCount = meterNames.Count;
                //如果配置文件数量大于当前 N2
                if (_meterCount > currCount)
                { //增加 （配合数 - 当前数）个新值
                    var maxNameId = _context.NewTMeterList.Any() ? _context.NewTMeterList.Max(m => m.NameId) : 0;
                    var startId = maxNameId > 0 ? maxNameId + 1 : 1;
                    var metersToAdd = _meterCount - currCount;
                    for (var i = startId; i < startId + metersToAdd; i++)
                    {
                        _context.NewTMeterList.Add(new() { Name = $"电表{i}" });
                    }
                    //（配置数 - 新增数 - 使用数） = 修改数
                    if (currCount > useCount)
                    {
                        for (var i = currCount - 1; i >= useCount; i--)
                        {
                            meterNames[i].IsDeleted = false;
                        }
                    }
                }
                else
                {
                    //（配置数 - 使用数） = 修改数
                    if (_meterCount > useCount)
                    {
                        for (var i = Math.Max(0, useCount - 1); i < _meterCount; i++)
                        {
                            meterNames[i].IsDeleted = false;
                        }
                    }
                    else if (_meterCount < useCount)
                    {
                        for (var i = Math.Max(0, useCount - 1); i >= _meterCount; i--)
                        {
                            meterNames[i].IsDeleted = true;
                        }
                    }
                }
                _context.SaveChanges();
            }
        }
    }
}
